import csv
import json

from aip import AipOcr

""" 你的 APPID AK SK """
APP_ID = '11322449'
API_KEY = 'EVyjdsDGim5jlRAPSf1wVAv5'
SECRET_KEY = 'eYXPid0PvAL9FK7BeCSylGd0lyEVj348'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

""" 读取图片 """


def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


image = get_file_content(r'C:\Users\Administrator\Desktop\test\table.jpg')

""" 调用通用文字识别, 图片参数为本地图片 """
j = client.tableRecognition(
    image, {"result_type": "excel"}, 100000
)
print(j)
# j = json.loads(s, encoding="utf-8")
# if j.get("result"):
#     items = j["result"]["result_data"]
#     print(items)
# filename = "filename"
# if j.get("result"):
#     items = j["result"]["result_data"]
#     print(items)
#     items = json.loads(items, encoding="utf-8")
#     items = items["forms"][0]["body"]
#     print(items)
#
#     items = sorted(items, key=lambda r: (r['row'], r['column']))
#     print(items)

# with open(f"{filename}.csv", "w", newline="", encoding="gbk") as datacsv:
#     csvwriter = csv.writer(datacsv, dialect=("excel"))
#     last_item_row_index = -1
#     # csv文件插入一行数据，把下面列表中的每一项放入一个单元格（可以用循环插入多行）
#     row_content_arr = []
#     for item in items:
#         current_item_row_index = int(item["row"][0])
#         current_item_content = item["word"]
#         if current_item_row_index == last_item_row_index:
#             row_content_arr.append(current_item_content)
#         else:
#             if last_item_row_index >= 0:
#                 csvwriter.writerow(row_content_arr)
#                 print(row_content_arr)
#             row_content_arr.clear()
#             last_item_row_index += 1
#             row_content_arr.append(current_item_content)
#     else:
#         csvwriter.writerow(row_content_arr)

# items = j["result"]["result_data"]["forms"][0]["body"]
# print(items)
# for item in items:
#     item_content = item["word"]
#     if item_content:
#         print(item_content)


# """ 如果有可选参数 """
# options = {}
# options["language_type"] = "CHN_ENG"
# options["detect_direction"] = "true"
# options["detect_language"] = "true"
# options["probability"] = "true"

# """ 带参数调用通用文字识别, 图片参数为本地图片 """
# client.basicGeneral(image, options)
#
# url = "https//www.x.com/sample.jpg"
#
# """ 调用通用文字识别, 图片参数为远程url图片 """
# client.basicGeneralUrl(url)
#
# """ 如果有可选参数 """
# options = {}
# options["language_type"] = "CHN_ENG"
# options["detect_direction"] = "true"
# options["detect_language"] = "true"
# options["probability"] = "true"
#
# """ 带参数调用通用文字识别, 图片参数为远程url图片 """
# client.basicGeneralUrl(url, options)
